package com.huangsm.book.designmodel.executor.diythreadpool;

import java.util.List;
import java.util.Vector;

/**
 * 自定义实现一个简单的线程池(单例模式)
 * 使用这个线程池，需要一个永不退出的线程与之配合。PThread就是这样一个线程。
 * @author huang
 * @date 2019/2/19
 */
public class ThreadPool {
    private static ThreadPool instance=null;

    //空闲的线程队列
    private List<PThread>idleThreads;
    //已有的线程总数
    private int threadCounter;
    private boolean isShutDown=false;

    private ThreadPool(){
        this.idleThreads=new Vector(5);
        threadCounter=0;
    }
    public int getCreatedThreadsCount(){
        return threadCounter;
    }
    //获取线程池的实例
    public synchronized static ThreadPool getInstance(){
        if (instance==null)
            return new ThreadPool();
        return instance;
    }
    //将线程放入池中
    protected synchronized void repool(PThread repoolingThread){
        if (!isShutDown){
            idleThreads.add(repoolingThread);
        }
        else {
            repoolingThread.shutDown();
        }
    }
    //停止池中所有进程
    public synchronized void shutdown(){
        isShutDown=true;
        for(int threadIndex=0;threadIndex<idleThreads.size();threadIndex++){
            PThread idleThread=(PThread)idleThreads.get(threadIndex);
            idleThread.shutDown();
        }
    }
    //执行任务
    public synchronized void start(Runnable target){
        PThread thread=null;
        //如果有空闲线程，则直接使用
        if (idleThreads.size()>0){
            int lastIndex=idleThreads.size()-1;
            thread=(PThread) idleThreads.get(lastIndex);
            idleThreads.remove(lastIndex);
            //立即执行这个任务
            thread.setTarget(target);
        }
        //没有空闲线程，则创建新线程
        else {
            threadCounter++;
            //创建新线程
            thread=new PThread(target,"PThread #"+threadCounter,this);
            //启动
            thread.start();
        }
    }

}
